import { getIdsFromHref } from '@/utils/setAssociated'
export const setTMToken = (userID: string, token: string) => {
  localStorage.setItem(`IM_TOKEN_${userID}`, token)
}

export const setTMUserID = (userID: string) => {
  localStorage.setItem(`IM_USERID_${userID}`, userID)
}

export const setTMFriendID = (userID: string, friendID: string) => {
  localStorage.setItem(`IM_FRIENDID_${userID}_${friendID}`, friendID)
}
export const setIMProfile = ({ imToken, userID, friendID }: any) => {
  setTMToken(userID, imToken)
  setTMUserID(userID)
  setTMFriendID(userID, friendID)
}

export const clearIMProfile = () => {
  if (process.env.CHAT_TEST) {
    localStorage.removeItem(`IM_TOKEN_${process.env.CHAT_TEST_USERID}`)
    localStorage.removeItem(`IM_USERID_${process.env.CHAT_TEST_USERID}`)
    localStorage.removeItem(`IM_FRIENDID_${process.env.CHAT_TEST_USERID}_${process.env.CHAT_TEST_FRIENDID}`)
    return
  }
  const arr = getIdsFromHref()
  if (arr.length === 2) {
    localStorage.removeItem(`IM_TOKEN_${arr[0]}`)
    localStorage.removeItem(`IM_USERID_${arr[0]}`)
    localStorage.removeItem(`IM_FRIENDID_${arr[0]}_${arr[1]}`)
  }

}

export const getIMToken = () => {
  if (process.env.CHAT_TEST) {
    return localStorage.getItem(`IM_TOKEN_${process.env.CHAT_TEST_USERID}`)

  }
  const arr = getIdsFromHref()
  if (arr.length === 2) {
    return localStorage.getItem(`IM_TOKEN_${arr[0]}`)
  }
}
export const getIMUserID = () => {
  if (process.env.CHAT_TEST) {
    return localStorage.getItem(`IM_USERID_${process.env.CHAT_TEST_USERID}`)
  }
  const arr = getIdsFromHref()
  if (arr.length === 2) {
    return localStorage.getItem(`IM_USERID_${arr[0]}`)
  }
}
export const getTMFriendID = () => {
  if (process.env.CHAT_TEST) {
    return localStorage.getItem(`IM_FRIENDID_${process.env.CHAT_TEST_USERID}_${process.env.CHAT_TEST_FRIENDID}`)
  }
  const arr = getIdsFromHref()
  if (arr.length === 2) {
    return localStorage.getItem(`IM_FRIENDID_${arr[0]}_${arr[1]}`)
  }
}

export const getAccessedFriendApplication = () =>
  localStorage.getItem(`${getIMUserID()}_accessedFriendApplications`)
    ? JSON.parse(localStorage.getItem(`${getIMUserID()}_accessedFriendApplications`)!)
    : []
export const getAccessedGroupApplication = () =>
  localStorage.getItem(`${getIMUserID()}_accessedGroupApplications`)
    ? JSON.parse(localStorage.getItem(`${getIMUserID()}_accessedGroupApplications`)!)
    : []

export const getWsUrl = () => localStorage.getItem('wsUrl') || process.env.WS_URL!
export const getApiUrl = () => localStorage.getItem('apiUrl') || process.env.API_URL!
export const getChatUrl = () => localStorage.getItem('chatUrl') || process.env.CHAT_URL!
export const getLogLevel = () =>
  localStorage.getItem('logLevel') || process.env.LOG_LEVEL!
